package cn.hd01.export;

import org.springframework.beans.factory.annotation.Autowired;

import cn.hd01.export.listener.RowProccessListener;
import cn.hd01.util.ValidationResult;
import cn.hd01.util.ValidationUtils;

import com.alibaba.fastjson.JSON;

public abstract class AbstractRowProccess<T> implements RowProccess<T> {

	@Autowired
	protected RowProccessListener listener;

	public AbstractRowProccess(RowProccessListener listener) {
		this.listener = listener;
	}

	@Override
	public void process(int index, String[] row) {
		try {
			T entity = mapper(row);
			validate(entity);
			process(entity);
			listener.onSuccess(index);
		} catch (Exception e) {
			listener.onFailure(index, e);
			throw e;
		}
	}

	public abstract T mapper(String[] row);

	public abstract void process(T obj);
	
	public abstract String[] mapper(T obj);

	public void validate(T obj) {
		ValidationResult result = ValidationUtils.validateEntity(obj);
		if (result.isHasErrors()) {
			throw new IllegalArgumentException(JSON.toJSONString(result.getErrorMsg()));
		}
	}

}
